import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:pass_log/app/core/utils/common.dart';
import 'package:pass_log/app/data/providers/type_provider.dart';
// import 'package:pass_log/app/core/utils/logger.dart';

typedef ObjItem = Map<String, dynamic>;

final tlp = Get.find<TypeListProvider>();

class TypeController extends GetxController {
  var typeBox = tlp.box;
  var typeList = tlp.list;
  var selectedIcon = {"icon": "60556", "fontFamily": "MaterialIcons"}.obs;

  // 更新分类列表
  void refreshType() {
    typeList.value = tlp.setDefaultType();
  }

  // 删除分类
  void deleteType(ObjItem item) {
    typeBox.delete(item["id"]);
    refreshType();
  }

  // 编辑分类
  void editType(String name, ObjItem item) {
    typeBox.put(item["id"], {
      "id": item["id"],
      "sort": item["sort"],
      "name": name,
      "icon": selectedIcon["icon"],
      "fontFamily": selectedIcon["fontFamily"],
    });
    refreshType();
    EasyLoading.showSuccess("编辑成功").then((value) {
      selectedIcon.value = {"icon": "60556", "fontFamily": "MaterialIcons"};
      Get.back();
    });
  }

  // 创建分类
  void createType(String name) {
    // 校验
    if (name.isEmpty) {
      EasyLoading.showToast("分类名称不能为空");
      return;
    }
    // 保存
    int sort;
    if (typeList.isNotEmpty) {
      sort = typeList.last["sort"] + 1;
    } else {
      sort = 1;
    }
    var id = getUnixMilliseconds();
    typeBox.put(id.toString(), {
      "id": id.toString(),
      "sort": sort,
      "name": name,
      "icon": selectedIcon["icon"],
      "fontFamily": selectedIcon["fontFamily"],
    });
    refreshType();
    EasyLoading.showSuccess("保存成功").then((value) {
      selectedIcon.value = {"icon": "60556", "fontFamily": "MaterialIcons"};
      Get.back();
    });
  }

  // 重排序分类
  void reorderType(int oldIndex, int newIndex) {
    var item = typeList.removeAt(oldIndex);
    typeList.insert(newIndex, item);
    for (var i = 0; i < typeList.length; i++) {
      typeList[i]["sort"] = i;
      typeBox.put(typeList[i]["id"], typeList[i]);
    }
    refreshType();
  }
}
